/* 
 * Copyright (c) 2019, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.boot.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.cory.boot.domain.CustomRuntimeException;
import com.cory.boot.domain.bean.Result;

/**
 * 统一异常处理
 * @author xiongcong
 * @date 2019-03-15
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandle {
    
    @ExceptionHandler(value = Exception.class)
    public Object handle(Exception exception, HttpServletRequest request, HttpServletResponse response) {
        
        int code = Result.FAIL;
        String message = "系统异常，请稍后重试";
        if (exception instanceof IllegalArgumentException) {
            message = "请求参数错误";
            log.error("", exception);
        } else if (exception instanceof CustomRuntimeException) {
            CustomRuntimeException ex = (CustomRuntimeException)exception;
            code = ex.getCode();
            message = ex.getMessage();
            log.error(message);
        } else {
            log.error("", exception);
        }
        
        if (isAjaxRequest(request)) {
            try {
                response.setCharacterEncoding("UTF-8");  
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().append(JSONObject.toJSONString(Result.custom(code, message)));
                return null;
            } catch (Exception e) {
                return null;
            } 
        }
        
        ModelAndView modelAndView = new ModelAndView("boot/message");
        modelAndView.addObject("message", message);
        return modelAndView;
        
    }
    
    public boolean isAjaxRequest(HttpServletRequest request) {
        String xReq = request.getHeader("x-requested-with");
        if (StringUtils.isNotBlank(xReq) && "XMLHttpRequest".equalsIgnoreCase(xReq)) {
            return true;
        }
        String contentType = request.getHeader("Content-Type");
        if (StringUtils.isNotBlank(contentType) && contentType.contains("application/json")) {
            return true;
        }
        return false;
    }
}
